package cn.chiship.bs.api.biz.controller;


import cn.chiship.bs.api.biz.pojo.dto.UserCaptchaLoginDto;
import cn.chiship.bs.api.biz.pojo.vo.CacheUserVO;
import cn.chiship.bs.api.biz.service.MemberUserService;
import cn.chiship.bs.api.biz.service.UpmsUserService;
import cn.chiship.bs.api.core.enums.LoginTypeEnum;
import cn.chiship.sdk.core.annotation.Authorization;
import cn.chiship.sdk.core.annotation.NoParamsSign;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.CacheConstants;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.util.ip.IpUtils;
import cn.chiship.bs.api.biz.pojo.vo.CacheRoleVo;
import cn.chiship.bs.api.biz.service.RedisService;
import cn.chiship.bs.api.biz.service.UserCacheService;
import cn.chiship.bs.api.core.constants.CommonCacheConstants;
import cn.chiship.sdk.third.wx.network.WxMiniProgramServicesUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录相关
 *
 * @author lijian
 */
@RestController
@RequestMapping("/sso")
@Api(tags = "登录控制器")
public class SsoController {
    private static final String STRING_MOBILE = "Mobile";
    private static final String STRING_SCAN = "scan";
    private static final String STRING_IS_C_L = "isConfirmLogin";

    @Resource
    private UpmsUserService upmsUserService;
    @Resource
    RedisService redisService;
    @Resource
    UserCacheService userCacheService;
    @Resource
    MemberUserService memberUserService;

    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
    })
    @PostMapping("login")
    public ResponseEntity<BaseResult> login(HttpServletRequest request, @RequestBody @Valid UserCaptchaLoginDto userCaptchaLoginDto) {

        String ip = IpUtils.getIpAddr(request);
        String verificationCode = userCaptchaLoginDto.getVerificationCode();
        verificationCode = verificationCode.toUpperCase();
        String key = CommonCacheConstants.buildKey(CacheConstants.REDIS_CAPTCHA_PREFIX);
        if (redisService.hget(key, verificationCode) == null) {
            return new ResponseEntity<>(BaseResult.error(BaseResultEnum.FAILED, "验证码错误"), HttpStatus.OK);


        }
        redisService.hdel(key, verificationCode);
        return new ResponseEntity<>(upmsUserService.login(
                request.getSession().getId(),
                userCaptchaLoginDto.getUsername(),
                userCaptchaLoginDto.getPassword(),
                ip,
                LoginTypeEnum.LOGIN_PC
        ), HttpStatus.OK);
    }


    @ApiOperation(value = "获得用户信息")
    @GetMapping("/getInfo")
    @Authorization
    public ResponseEntity<BaseResult> getInfo() {
        CacheUserVO userVO = userCacheService.getUser();
        Map<String, Object> map = new HashMap<>(2);
        map.put("admin", userVO);
        List<CacheRoleVo> roleVos = userVO.getCacheRoleVos();
        List<String> roles = new ArrayList<>();
        if (roleVos != null) {
            for (CacheRoleVo roleVo : roleVos) {
                roles.add(roleVo.getRoleCode());
            }
        }
        map.put("roles", roles);
        return new ResponseEntity<>(BaseResult.ok(map), HttpStatus.OK);
    }

    /**
     * 注销登录
     *
     * @return
     */
    @ApiOperation(value = "注销登录")
    @PostMapping("/logout")
    @Authorization
    public ResponseEntity<BaseResult> logout() {
        userCacheService.removeUser();
        return new ResponseEntity<>(BaseResult.ok(), HttpStatus.OK);
    }

    @ApiOperation(value = "小程序Code换取Session")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "小程序登录获得的Code", required = true, dataType = "String", paramType = "query"),
    })
    @GetMapping("/code2Session")
    @NoParamsSign
    public ResponseEntity<BaseResult> code2Session(@RequestParam(value = "code") String code) {
        WxMiniProgramServicesUtil wxMiniProgramServicesUtil = WxMiniProgramServicesUtil.getInstance().config();
        return new ResponseEntity<>(wxMiniProgramServicesUtil.code2Session(code), HttpStatus.OK);

    }

    @ApiOperation(value = "小程序登录")
    @ApiImplicitParams({
    })
    @PostMapping("/appletLogin")
    @NoParamsSign
    public ResponseEntity<BaseResult> appletLogin(HttpServletRequest request, @RequestBody @Valid String openId) {
        BaseResult baseResult = memberUserService.appletLogin(openId, IpUtils.getIpAddr(request));
        return new ResponseEntity<>(baseResult, HttpStatus.OK);
    }

}
